'use strict';
import React, {PropTypes} from 'react';
import {
    ListView,
    View,
    Text,
    TouchableOpacity,
    StyleSheet,
} from 'react-native';
import Global from '../Commom/GlobalConst';

let itemsHeight = 0;

const styles = StyleSheet.create({
    btnStyle: {
        textAlign: 'center',
        padding: 10,
        backgroundColor: '#ffff00',
        textAlignVertical: 'center',
    }
});

/**
 *  可以上拉刷新的ListView
 */
class OnRefreshListView extends React.Component {

    constructor(props) {
        super(props);
        itemsHeight = 0;
        this.state = {
            flag: true,
        }
    }

    _onLayout(event) {

        if (itemsHeight > Global.Const.size.height - 125 && !this.state.flag) {
            return;
        }
        if (itemsHeight < Global.Const.size.height - 125) {
            itemsHeight = event.nativeEvent.layout.height + itemsHeight;
        }
        if (itemsHeight > Global.Const.size.height - 125) {
            this.setState({
                flag: false,
            })
        }
    }

    render() {
        let {
            dataSource,
            renderRow,
            contentContainerStyle,
            onRefreshItemData,
            btnStyle
        } = this.props;
        return (
            <View>
                <ListView
                    dataSource={dataSource}
                    renderRow={(rowData) => renderRow(rowData)}
                    onLayout={(event) => this._onLayout(event)}
                    contentContainerStyle={contentContainerStyle}
                    onEndReached={
                        this.state.flag ?
                            ()=> {
                            }
                            : () =>onRefreshItemData()}
                    onEndReachedThreshold={100}
                />
                {/*{*/}
                    {/*this.state.flag ?*/}
                        {/*<TouchableOpacity*/}
                            {/*style={{*/}
                                {/*position: 'absolute',*/}
                                {/*bottom: -40,*/}
                                {/*left: 0,*/}
                                {/*right: 0,*/}
                            {/*}}*/}
                            {/*onPress={() => {*/}
                                {/*onRefreshItemData()*/}
                            {/*}}>*/}
                            {/*<Text style={[styles.btnStyle, btnStyle]}>加载更多</Text>*/}
                        {/*</TouchableOpacity> :*/}
                        {/*<View/>*/}
                {/*}*/}
            </View>
        )
    }
}

OnRefreshListView.propTypes = {
    dataSource: PropTypes.object.isRequired,
    renderRow: PropTypes.func.isRequired,
    onRefreshItemData: PropTypes.func.isRequired,
    contentContainerStyle: View.propTypes.style,
    btnStyle: View.propTypes.style,
};

export default OnRefreshListView;